package com.usian.wemedia.gateway.filter;

import com.usian.jwt.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class WmeidaGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断当前的请求是否为登录，如果是，直接放行,当前是登录接口的访问，不做校验
        if (request.getURI().getPath().contains("/login/in")) {
            return chain.filter(exchange);
        }
        //3.获取当前用户的请求头jwt信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //4.判断当前令牌是否存在
        if (StringUtils.isBlank(token)) {
            String json = "{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        try {
            //5.如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
            Claims claims =AppJwtUtil.getClaimsBody(token);
            if (claims==null){
                String json = "{\"errorMsg\":\"token is not\"}";
                return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
            }
            int i = AppJwtUtil.verifyToken(claims);
            if (i == 0 || i == -1) {
                Integer id = (Integer)claims.get("id");
                String refreshToken=null;
                if (i==0){
                    refreshToken=AppJwtUtil.getToken(id.longValue());
                }
                HttpHeaders headerParam = new HttpHeaders();
                headerParam.add("userId",id+"");
                if (refreshToken!=null)headerParam.add("refreshToken",refreshToken);
                ServerHttpRequest newRequest = request.mutate().headers(httpHeaders -> httpHeaders.addAll(headerParam)).build();
                exchange.mutate().request(newRequest).build();
            }
        }catch (Exception e){
            e.printStackTrace();
            //想客户端返回错误提示信息
            String json = "{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        //6.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
